package com.wwu.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwu.common.utils.AssertUtil;
import com.wwu.common.utils.SpringUtils;
import com.wwu.common.web.ResultObj;
import com.wwu.common.redis.RedisConst;
import com.wwu.common.redis.RedisUtil;
import com.wwu.system.common.security.SecurityUtil;
import com.wwu.system.entity.SysConfig;
import com.wwu.system.mapper.SysConfigMapper;
import com.wwu.system.service.ISysConfigService;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.net.InetAddress;

/**
 * 系统配置服务实现类
 * @author 一蓑烟雨
 * @date 2021-10-26
 * @version 1.0.0
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {
    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取系统配置信息，没有则新增
     * @return com.wwu.system.entity.SysConfig
     * @author 一蓑烟雨
     * @date 2023/5/30 18:33
     */
    @Override
    public SysConfig getSysConfig() {
        //从缓存中获取配置信息
        SysConfig configRedis = JSON.parseObject(String.valueOf(redisUtil.getValue(RedisConst.Key.SYS_CONFIG)),SysConfig.class);
        if(null != configRedis){
            return  configRedis;
        }

        //若缓存中不存在则查询数据库
        SysConfig sysConfig = this.getOne(new QueryWrapper<>());
        //更新缓存
        this.sysConfigCache();

        return sysConfig;
    }

    /**
     * 更新系统配置图片
     * @param imageType  图片类型
     * @param file   文件信息
     * @return com.wwu.common.web.ResultObj
     * @author 一蓑烟雨
     * @date 2023/8/12 10:21
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public ResultObj updateSysConfigImage(String imageType, MultipartFile file) {
        AssertUtil.isTrue(!StringUtils.hasText(imageType),"图片类型不能为空");
        AssertUtil.isTrue(ObjectUtils.isEmpty(file),"图片类型不能为空");

        try {
            //获取编译后的路径
            String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/images/";
            System.out.println(filePath);
            System.out.println(filePath.replace("target/classes/","src/main/resources/"));
            //获取应用信息
            ApplicationContext applicationContext = SpringUtils.getApplicationContext();
            Environment env = applicationContext.getEnvironment();
            String ip = InetAddress.getLocalHost().getHostAddress();
            String port = env.getProperty("server.port");
            String path = env.getProperty("server.servlet.context-path");

            //获取配置信息
            SysConfig sysConfig =getSysConfig();

            String imgName = null;
            String appPath = null;
            if("sysLogo".equals(imageType)){
                imgName = "logo.png";
                appPath = "http://" + ip + ":" + port + path + "/images/logo.png";
                sysConfig.setSystemLogo(appPath);
            }else if("loginBack".equals(imageType)){
                imgName = "loginbg.png";
                appPath = "http://" + ip + ":" + port + path + "/images/loginbg.png";
                sysConfig.setLoginBackImg(appPath);
            }else if("webIcon".equals(imageType)){
                imgName = "favicon.ico";
                appPath = "http://" + ip + ":" + port + path + "/images/favicon.ico";
                sysConfig.setWebsiteIcon(appPath);
            }

            //上传文件
            file.transferTo(new File(filePath+imgName));
            //更新数据库
            this.updateSysConfig(sysConfig);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultObj.except(e.getMessage());
        }
        return ResultObj.success();
    }

    /**
     * 更新系统配置信息
     * @param sysConfig
     * @return com.wwu.common.web.ResultObj
     * @author 一蓑烟雨
     * @date 2023/5/30 18:34
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public ResultObj updateSysConfig(SysConfig sysConfig) {
        if(null == sysConfig || sysConfig.getRecordId() == null){
            return ResultObj.error("配置信息错误，更新失败");
        }

        sysConfig.setModifier(SecurityUtil.getCurrUserName());
        this.updateById(sysConfig);

        //更新缓存
        this.sysConfigCache();

        return ResultObj.success();
    }

    /**
     * 查询字典数据，在项目启动时加载
     * @return com.wwu.common.web.ResultObj
     * @author 一蓑烟雨
     * @date 2023/7/20 16:14
     */
    @Override
    public ResultObj sysConfigCache() {
        SysConfig sysConfig = this.getOne(new QueryWrapper<>());
        if(null == sysConfig ){
            sysConfig =  new SysConfig();
            sysConfig.setCreator(SecurityUtil.getCurrUserName());
            this.save(sysConfig);
        }
        //将配置信息保存到缓存中
        redisUtil.setValue(RedisConst.Key.SYS_CONFIG, JSON.toJSONString(sysConfig));

        return ResultObj.success("系统配置缓存更新成功");
    }
}
